package com.example.administrator.base.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.DispatchBean;
import com.example.administrator.base.bean.PointMessageBean;
import com.example.administrator.base.R;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.SharedPreferencesUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PointMessage extends BaseActivity {

    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.list)
    ListView list;
    @InjectView(R.id.swip)
    TwinklingRefreshLayout swip;
    List<String> data;
    List<String> dataid;
    int page;
    String totlePage;
    ArrayAdapter<String> adapter;
    SweetAlertDialog sweetAlertDialog;
    List<PointMessageBean.ChildrenAreaPositionInfoBean> listbean;
    private String type = "1";//判断入口

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_message);
        ButterKnife.inject(this);
        Intent intent = getIntent();
        final String adddispatchlist = intent.getStringExtra("adddispatchlist");
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        data = new ArrayList<>();
        dataid = new ArrayList<>();
        listbean = new ArrayList<>();
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("停放点信息");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        page = 1;
        sweetAlertDialog.show();
        getPoint(page);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, data);
        list.setAdapter(adapter);
        //给Listview子条目添加点击事件
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s = dataid.get(position);
                String item = data.get(position);
                EventBus.getDefault().post(new DispatchBean(s, item));
                if (type.equals(adddispatchlist)) {
                    finish();
                }
            }
        });

        swip.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                data.clear();
                page = 1;
                listbean.clear();
                getPoint(page);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                if (page == Integer.parseInt(totlePage)) {
                    swip.finishLoadmore();
                    Toast.makeText(PointMessage.this, "别拉了，已经到底啦！", Toast.LENGTH_SHORT).show();
                } else {
                    page += 1;
                    getPoint(page);
                }
            }
        });
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }


    /*获取定位点列表*/
    public void getPoint(final int number) {
        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(PointMessage.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "LOCATINGSTOPINFO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(PointMessage.this, "adminId", "")))
                .add("childrenAreaId", String.valueOf(SharedPreferencesUtils.getParam(PointMessage.this, "childrenAreaId", "")))
                .add("page", String.valueOf(number))
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/operationperson?")
                .post(formBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("33710", string);
                        final PointMessageBean mse = GsonTools.changeGsonToBean(string, PointMessageBean.class);
                        if (mse == null) {
                            return;
                        }
                        if (mse.getCode() == 1) {
                            totlePage = mse.getTotalPages();
                            Log.i("33710", "tt:"+totlePage);
                            listbean.addAll(mse.getChildrenAreaPositionInfo());
                            for (int i = 0; i < mse.getChildrenAreaPositionInfo().size(); i++) {
                                data.add(mse.getChildrenAreaPositionInfo().get(i).getPointName());
                                dataid.add(mse.getChildrenAreaPositionInfo().get(i).getId());
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                    swip.finishRefreshing();
                                    swip.finishLoadmore();
                                    sweetAlertDialog.dismiss();
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(PointMessage.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }

                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
